const connect = require('connect');
const getRawBody = require('raw-body');
const bodyParser = require('body-parser');

connect()
  .use(type('application/x-www-form-urlencoded', { limit: '64kb' }))
  .use(type('application/json', getRawBody({ limit: '32kb' })))
  .use(type('image', { limit: '2mb' }))
  .use(type('video', { limit: '300mb' }))
  .use(bodyParser())
  .use(hello)
  .listen(3000);

function type(value, opts) {
  return function (req, res, next) {
    const ct = req.headers['content-type'] || '';
    if (!ct.includes(value)) {
      return next();
    } else {
      getRawBody(req, opts, (err) => {
        if (err) {
          return next(err)
        } else {
          next();
        }
      })
    }
  };
}

function hello(req, res) {
  res.end('hello\n');
}
